package com.yxt.ui;


import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ZoomButtonsController;

import com.yxt.common.http.HttpUrlExtract;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.sys.StringUtil;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.ImageViewTouchBase;
import com.yxt.common.ui.RotateBitmap;

public class RadarDispalyActivity extends Activity {
	private static final String TAG = "DisplayImage";
    private static final int FLING_MIN_DISTANCE = 100;
    private static final int FLING_MIN_VELOCITY = 200;
	private RadarTouch mImageView;
	private ImageView imageStar;
	private Bitmap bitmap;
	private DisplayMetrics dm;
	private int displayWidth;
    private int displayHeight;
    private RotateBitmap rotateBitmap;
    private GestureDetector mGestureDetector;
    
	
	public void onCreate(Bundle savedInstanceState) {
//		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
//		setContentView(R.layout.radar);   //软件activity的布局
//		ActivityStackControlUtil.add(this);	
//		initComponent();
		
		super.onCreate(savedInstanceState);
	
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        /* 加载display.xml Layout */
        setContentView(R.layout.radar);
        
        mImageView = (RadarTouch) findViewById(R.id.radarimage);
        mImageView.setEnableTrackballScroll(true);
        
        //bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.water_legend);
        
        refresh(true);
        
        /* 取得屏幕分辨率大小 */
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        displayWidth = dm.widthPixels;
        displayHeight = dm.heightPixels;
        
        rotateBitmap = new RotateBitmap(bitmap, 123);
        mImageView.setImageRotateBitmapResetBase(rotateBitmap, true); 
        
        RotateBitmap rotateBitmap = new RotateBitmap(bitmap);
        mImageView.setImageRotateBitmapResetBase(rotateBitmap, true);
        mImageView.setImageBitmap(bitmap);

        setupZoomButtonController(mImageView);
        
        mGestureDetector = new GestureDetector(this, new MyGestureListener());
//      setupOnScreenControls(findViewById(R.id.rootLayout), mImageView);
        findViewById(R.id.layoutradar).setOnTouchListener(rootListener);

	}
	final OnTouchListener buttonListener = new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            scheduleDismissOnScreenControls();
            return false;
        }
    };
    OnTouchListener rootListener = new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            buttonListener.onTouch(v, event);
            mGestureDetector.onTouchEvent(event);

            // We do not use the return value of
            // mGestureDetector.onTouchEvent because we will not receive
            // the "up" event if we return false for the "down" event.
            return true;
        }
    };
    private void hideOnScreenControls() {

    }

    private final Runnable mDismissOnScreenControlRunner = new Runnable() {
        public void run() {
            hideOnScreenControls();
        }
    };
    
    private void scheduleDismissOnScreenControls() {
        // mHandler.removeCallbacks(mDismissOnScreenControlRunner);
        // mHandler.postDelayed(mDismissOnScreenControlRunner, 2000);
    }
    
    private class MyGestureListener extends
    GestureDetector.SimpleOnGestureListener {

			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2,
			        float distanceX, float distanceY) {
			    // if (mPaused) return false;
				RadarTouch imageView = mImageView;
			    if (imageView.getScale() > 1F) {
			        imageView.postTranslateCenter(-distanceX, -distanceY);
			    }
			    return true;
			}
			
			@Override
			public boolean onSingleTapUp(MotionEvent e) {
			    // if (mPaused) return false;
			    // setMode(MODE_NORMAL);
			    return true;
			}
			
			@Override
			public boolean onSingleTapConfirmed(MotionEvent e) {
			    // if (mPaused) return false;
			    // showOnScreenControls();
			    scheduleDismissOnScreenControls();
			    return true;
			}
			
			@Override
			public boolean onDoubleTap(MotionEvent e) {
			    // if (mPaused) return false;
				RadarTouch imageView = mImageView;
			
			    // Switch between the original scale and 3x scale.
			    if (imageView.getScale() > 2F) {
			        mImageView.zoomTo(1f);
			    } else {
			        mImageView.zoomToPoint(3f, e.getX(), e.getY());
			    }
			    return true;
			}
	}
    
	private void setupZoomButtonController(final View ownerView) {
        Log.d(TAG,
                "\r\n\r\n\r\nmZoomButtonsControllermZoomButtonsControllermZoomButtonsController:"
                        + ownerView);
        mZoomButtonsController = new ZoomButtonsController(ownerView);
        mZoomButtonsController.setAutoDismissed(false);
        mZoomButtonsController.setZoomInEnabled(true);
        mZoomButtonsController.setZoomOutEnabled(true);
        mZoomButtonsController.setZoomSpeed(100);
        mZoomButtonsController
                .setOnZoomListener(new ZoomButtonsController.OnZoomListener() {
                    public void onVisibilityChanged(boolean visible) {
                        if (visible) {
                            updateZoomButtonsEnabled();
                        }
                    }

                    public void onZoom(boolean zoomIn) {
                        Log.d(TAG, "zoomIn:" + zoomIn);
                        if (zoomIn) {
                            mImageView.zoomIn();
                        } else {
                            mImageView.zoomOut();
                        }
                        mZoomButtonsController.setVisible(true);
                        updateZoomButtonsEnabled();
                    }
                });
    }
	 @Override
	    public void onWindowFocusChanged(boolean hasFocus) {
	        if (hasFocus)
	            mZoomButtonsController.setVisible(true);
	        
	        Log.d(TAG, "\r\n\r\nmImageView width:"+mImageView.getWidth());
	        Log.d(TAG, "mImageView height:"+mImageView.getHeight());
//	        mImageView.setZoomfloat(4f);
	        Log.d(TAG, "\r\n\r\nmScreen Width:"+displayWidth);
	        Log.d(TAG, "mScreenHeight height:"+displayHeight);
	        
//	        mImageView.postTranslateCenter(-0, -0);
	        
	        RectF rect = new RectF(0, 0, rotateBitmap.getBitmap().getWidth(),
	        		rotateBitmap.getBitmap().getHeight());
	        Matrix m = mImageView.getImageViewMatrix();
	        m.mapRect(rect);
	        float height = rect.height();
	        float width = rect.width();

	        float deltaX = 0, deltaY = 0;

	            int viewHeight = mImageView.getHeight();
	            if (height < viewHeight) {
	                deltaY = (viewHeight - height) / 2 - rect.top;
	            } else if (rect.top > 0) {
	                deltaY = -rect.top;
	            } else if (rect.bottom < viewHeight) {
	                deltaY = mImageView.getHeight() - rect.bottom;
	            }
	            
	            int viewWidth = mImageView.getWidth();
	            if (width < viewWidth) {
	                deltaX = (viewWidth - width) / 2 - rect.left;
	            } else if (rect.left > 0) {
	                deltaX = -rect.left;
	            } else if (rect.right < viewWidth) {
	                deltaX = viewWidth - rect.right;
	            }
	        
	        
	        mImageView.zoomToPoint(2f, 0, 0);
	        
//	        mImageView.postTranslateCenter(-(width*4-mScreenWidth)/2, -(height*4-mScreenHeight)/2);
	        mImageView.postTranslateCenter(-(width*4-displayWidth), -(height*4-displayHeight));
	        Thread t = new MovePosition();
//	        t.start();
	        super.onWindowFocusChanged(hasFocus);
	    }
	    
	    int x = 0;
	    int y = 0;
	    boolean flag = true;
	    class MovePosition extends Thread{

	        @Override
	        public void run() {
	            while(flag){
	                try {
	                    this.currentThread().sleep(100);
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }
	                mChangeBg.sendEmptyMessage(3);
	            }
	        }
	        
	    }

	    
	    private Handler mChangeBg = new Handler() {
	        public void handleMessage(Message msg) {
	            x+=1;
	            y+=1;
	            Log.d(TAG, "ddddddddd:"+x+"  "+y);
//	            if(480*4-mScreenHeight==y){
//	                flag = false;
//	            }
	            mImageView.postTranslateCenter(-1, -1);
	            mImageView.postTranslate(1, 1);
	            
	            
	        }
	    };
	
	private ZoomButtonsController mZoomButtonsController;
    private void updateZoomButtonsEnabled() {
    	RadarTouch imageView = mImageView;
        float scale = imageView.getScale();
        // mZoomButtonsController.setZoomInEnabled(scale < imageView.mMaxZoom);
        // mZoomButtonsController.setZoomOutEnabled(scale > 1);
        mZoomButtonsController.setZoomInEnabled(true);
        mZoomButtonsController.setZoomOutEnabled(true);
    }
    public void onClick(View v) {

    }

//	private void initComponent(){
//		refresh(false);
//		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
//		btnBackHome.setOnClickListener(new OnClickListener(){
//			public void onClick(View arg0) {
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), MainActivity.class);
//				startActivity(intent);
//			}
//		});
//		imageStar = (ImageView)findViewById(R.id.imageStar);
//		imageStar.setOnTouchListener(new MulitPointTouchListener());
//		zoom();
//	}

	
	public void refresh(boolean refresh){
		Intent intent = getIntent();
		String itemId = intent.getStringExtra("itemId");
		Map<String, String> menu = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get(itemId);
		String server = menu.get("server");
		String params = menu.get("parameters");
		if (StringUtil.isEmpty(params)) {
			bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo_error);
		} else {
			//部分参数以@分隔 部分有空格分隔
			String name = "";
			String type = "";
			if (params.indexOf("@") > -1) {
				params = params.split("=")[1];
				String[] array = params.split("@");
				name = array[0];
				type = array[1];
			} else {
				name = CommConstant.Photo.DEFAULT_LEIDA_NAME;
				if (params.indexOf("photo") > 0 ) {
					type = params.substring(params.lastIndexOf("=")+1);
				} else {
					type = CommConstant.Photo.DEFAULT_LEIDA_CODE;
				}
			}
			
			String url = server+"photo/Photo.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&photoid="+ URLEncoder.encode(name) +"&type="+type;
			String photo = CommConstant.Main.CURRENT_TEMPLATE_CODE + "_" + itemId + ".bmp";
			File imageFile = new File(CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.PHOTO_LOCATION +photo);
			if (!imageFile.exists()){
				if(refresh)
				HttpUrlExtract.downloadBitmap(url,photo);
			}
			try {
				bitmap = BitmapFactory.decodeStream(new FileInputStream(imageFile));
			} catch (Exception e) {
				bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo_error);
			}
		}
	}
	
//	private void zoom() {
//		int screenWidth, screenHeight;
//		WindowManager windowManager = getWindowManager();
//		Display display = windowManager.getDefaultDisplay();
//		screenWidth = display.getWidth();
//		screenHeight = display.getHeight();
//		imageStar.setImageDrawable(ImageUtil.zoomPicture(getApplicationContext(), bitmap, screenWidth, screenHeight, "10", "10", "2"));
//	}
//
//	public void onConfigurationChanged(Configuration newConfig) {
//		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//			// 当前为横屏， 在此处添加额外的处理代码
//			zoom();
//		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//			// 当前为竖屏， 在此处添加额外的处理代码
//			zoom();
//		}
//		super.onConfigurationChanged(newConfig);
//	}
//	
	protected void onDestroy() {     
        super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}

//This is a cache for Bitmap displayed in ViewImage (normal mode, thumb only).
class BitmapRadar implements ImageViewTouchBase.Recycler {
    public static class Entry {
        int mPos;
        Bitmap mBitmap;

        public Entry() {
            clear();
        }

        public void clear() {
            mPos = -1;
            mBitmap = null;
        }
    }

    private final Entry[] mCache;

    public BitmapRadar(int size) {
        mCache = new Entry[size];
        for (int i = 0; i < mCache.length; i++) {
            mCache[i] = new Entry();
        }
    }

    // Given the position, find the associated entry. Returns null if there is
    // no such entry.
    private Entry findEntry(int pos) {
        for (Entry e : mCache) {
            if (pos == e.mPos) {
                return e;
            }
        }
        return null;
    }

    // Returns the thumb bitmap if we have it, otherwise return null.
    public synchronized Bitmap getBitmap(int pos) {
        Entry e = findEntry(pos);
        if (e != null) {
            return e.mBitmap;
        }
        return null;
    }

    public synchronized void put(int pos, Bitmap bitmap) {
        // First see if we already have this entry.
        if (findEntry(pos) != null) {
            return;
        }

        // Find the best entry we should replace.
        // See if there is any empty entry.
        // Otherwise assuming sequential access, kick out the entry with the
        // greatest distance.
        Entry best = null;
        int maxDist = -1;
        for (Entry e : mCache) {
            if (e.mPos == -1) {
                best = e;
                break;
            } else {
                int dist = Math.abs(pos - e.mPos);
                if (dist > maxDist) {
                    maxDist = dist;
                    best = e;
                }
            }
        }

        // Recycle the image being kicked out.
        // This only works because our current usage is sequential, so we
        // do not happen to recycle the image being displayed.
        if (best.mBitmap != null) {
            best.mBitmap.recycle();
        }

        best.mPos = pos;
        best.mBitmap = bitmap;
    }

    // Recycle all bitmaps in the cache and clear the cache.
    public synchronized void clear() {
        for (Entry e : mCache) {
            if (e.mBitmap != null) {
                e.mBitmap.recycle();
            }
            e.clear();
        }
    }

    // Returns whether the bitmap is in the cache.
    public synchronized boolean hasBitmap(int pos) {
        Entry e = findEntry(pos);
        return (e != null);
    }

    // Recycle the bitmap if it's not in the cache.
    // The input must be non-null.
    public synchronized void recycle(Bitmap b) {
        for (Entry e : mCache) {
            if (e.mPos != -1) {
                if (e.mBitmap == b) {
                    return;
                }
            }
        }
        b.recycle();
    }
}
class RadarTouch extends ImageViewTouchBase {
    private final RadarDispalyActivity mViewImage;
    private boolean mEnableTrackballScroll;

    public RadarTouch(Context context) {
        super(context);
        mViewImage = (RadarDispalyActivity) context;
    }

    public RadarTouch(Context context, AttributeSet attrs) {
        super(context, attrs);
        mViewImage = (RadarDispalyActivity) context;
    }

    public void setEnableTrackballScroll(boolean enable) {
        mEnableTrackballScroll = enable;
    }

    protected void postTranslateCenter(float dx, float dy) {
        super.postTranslate(dx, dy);
        center(true, true);
    }

    private static final float PAN_RATE = 20;

    // This is the time we allow the dpad to change the image position again.
    private long mNextChangePositionTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (mViewImage.mPaused)
//            return false;

        // Don't respond to arrow keys if trackball scrolling is not enabled
        if (!mEnableTrackballScroll) {
            if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP)
                    && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT)) {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
